import React, {useEffect, useState} from 'react';
import {Button, Card, Carousel, Form, Input, Layout, List, Menu, message, Tag, Typography} from 'antd';
import {
  HomeOutlined,
  InfoCircleOutlined,
  ProfileOutlined,
  SearchOutlined,
  SignatureOutlined,
  UserOutlined
} from '@ant-design/icons';
import styles from './index.less';
import {attendExam, getCurrentUser, getExamList} from "@/services/ant-design-pro/api";
import '../../../../public/css/question_style.css'
import {ModalForm, ProFormRadio, ProFormTextArea} from "@ant-design/pro-components";
import {Span} from "next/dist/server/lib/trace/tracer";

const { Title, Text } = Typography;

const HomePage: React.FC = () => {

  const [examList, setExamList] = useState<API.Exam[]>([])
  const [questionList, setQuestionList] = useState<API.ExamAttendResult[]>([])
  const [loginUser, setLoginUser] = useState<API.CurrentUserResult>()
  const [questionModalOpen, handleQuestionModalOpen] = useState<boolean>(false)
  const [answerForm] = Form.useForm()

  // 加载考试数据
  const loadExamData = async () => {
    const res = await getExamList()
    if (res.code === 200 && res?.data) {
      message.success('获取考试列表成功!')
      setExamList(res.data)
    } else {
      message.error('获取考试列表失败!')
    }
  }

  // 加载用户数据
  const loadUserData = async () => {
    // 本地存储获取token TODO: 换成全局状态库
    const token = JSON.parse(localStorage.getItem("user_token"))
    const res = await getCurrentUser({
      token: token,
    })
    if (res.code === 200 && res?.data) {
      setLoginUser(res.data)
    } else {
      console.log(res.msg)
    }
  }

  // 点击参加考试处理函数
  const handleAttendExamClick = async (examId: number) => {
    // 本地存储获取token TODO: 换成全局状态库
    const token = JSON.parse(localStorage.getItem("user_token"))
    if (!token) {
      message.error('请先登录!')
      location.href = '/user/login'
    }
    const res = await attendExam({
        token: token,
        examId: examId
    })
    if (res.code === 200 && res?.data) {
      message.success('报名考试成功!')
      setQuestionList(res.data)
      handleQuestionModalOpen(true)
    } else {
      message.error(res.msg)
    }
  }

  useEffect(() => {
    // 加载考试数据
    loadExamData()
    // 加载登录用户数据
    loadUserData()
  }, [])

  return (
    <>
      <Layout className={styles.layout}>
        <Layout.Header className={styles.header}>
          <div className={styles.logo}>
            <>
              <SignatureOutlined />
                <a href={"/front/home"}><span> 米饭在线考试系统</span></a>
            </>
          </div>
          <Menu
            theme="dark"
            mode="horizontal"
            defaultSelectedKeys={['1']}
            className={styles.menu}
          >
            <Menu.Item key="1" icon={<HomeOutlined />}>首页</Menu.Item>
            <Menu.Item key="2" icon={<ProfileOutlined />}>我参加的考试</Menu.Item>
            <Menu.Item key="3" icon={<InfoCircleOutlined />}>关于我们</Menu.Item>
          </Menu>
          <div className={styles.search}>
            <Input
              placeholder="搜索考试"
              prefix={<SearchOutlined />}
              style={{ width: 200 }}
            />
          </div>
          { loginUser?.userAccount ? <Tag icon={<UserOutlined />}>{loginUser?.userAccount}</Tag> : <Button type="primary" icon={<UserOutlined />} onClick={() => {location.href = '/user/login'}}>登录</Button>}
        </Layout.Header>

        <Layout.Content className={styles.content}>
          <Carousel autoplay className={styles.carousel}>
            <div>
              <img
                src="/images/banner1.jpg"
                alt="Banner 1"
                className={styles.carouselImage}
              />
            </div>
            <div>
              <img
                src="/images/banner2.jpg"
                alt="Banner 2"
                className={styles.carouselImage}
              />
            </div>
            <div>
              <img
                src="/images/banner3.jpg"
                alt="Banner 3"
                className={styles.carouselImage}
              />
            </div>
            <div>
              <img
                src="/images/banner4.png"
                alt="Banner 4"
                className={styles.carouselImage}
              />
            </div>
          </Carousel>

          <List
            className={styles.examList}
            grid={{ gutter: 16, column: 4 }}
            dataSource={examList}
            renderItem={(exam) => (
              <List.Item>
                <Card
                  title={exam.examName}
                  extra={<Text type="secondary">{exam.examUser.userAccount}</Text>}
                >
                  <div className={styles.examInfo}>
                    <Text>开始时间: {exam.examStartTime}</Text>
                    <Text>结束时间: {exam.examEndTime}</Text>
                    <Text>时长: {exam.examDuration}分钟</Text>
                    <Text>总分: {exam.examTotalScore}分</Text>
                    <Text>题数: {exam.examTotalCount}道</Text>
                    <Button type="primary" onClick={() => {
                      // 设置考试id
                      answerForm.setFieldValue("examId", exam.examId);
                      answerForm.setFieldValue("userId", loginUser.userId);
                      handleAttendExamClick(exam.examId)
                    }}
                    >
                      参加考试
                    </Button>
                  </div>
                </Card>
              </List.Item>
            )}
          />
        </Layout.Content>
      </Layout>
      <ModalForm
        title="试卷内容"
        form={answerForm}
        onFinish={() => {
          const examSubmitParams = {
            userId: answerForm.getFieldValue("userId"),
            examId: answerForm.getFieldValue("examId"),
            answers: {},
          }
          questionList.map((question) => {
              let questionAnswer = answerForm.getFieldValue(question.questionId);
              examSubmitParams.answers[question.questionId] = questionAnswer;
              return question;
          });
          // 提交试卷答案
          console.log(examSubmitParams)
        }}
        open={questionModalOpen}
        onOpenChange={handleQuestionModalOpen}
        footer={null}
        className="paper-modal"
        width={800}
      >
        <div className="paper-content">
          <h2 className="paper-title">试卷内容</h2>
          <div className="question-list">
            {questionList.map((question, index) => (
              <div key={question.questionId} className="question-item">
                <div className="question-header">
                  <span className="question-number">{index + 1}. </span>
                  <span className="question-type">
                    {question.questionTypeId === 1 && "单选题"}
                    {question.questionTypeId === 3 && "判断题"}
                    {question.questionTypeId === 6 && "简答题"}
                  </span>
                </div>
                <div className="question-text">{question.questionName}</div>
                {question.questionTypeId === 1 && (
                  <>
                    <ul className="option-list">
                      <li className="option-item">
                        <span className="option-label">A. </span>
                        <span className="option-content">{question.optionA}</span>
                      </li>
                      <li className="option-item">
                        <span className="option-label">B. </span>
                        <span className="option-content">{question.optionB}</span>
                      </li>

                      <li className="option-item">
                        <span className="option-label">C. </span>
                        <span className="option-content">{question.optionC}</span>
                      </li>

                      <li className="option-item">
                        <span className="option-label">D. </span>
                        <span className="option-content">{question.optionD}</span>
                      </li>
                    </ul>
                    <div className="single-choice-answer">
                      <ProFormRadio.Group
                        name={question.questionId}
                        label=""
                        options={[
                          {
                            label: '选项A',
                            value: 'A',
                          },
                          {
                            label: '选项B',
                            value: 'B',
                          },
                          {
                            label: '选项C',
                            value: 'C',
                          },
                          {
                            label: '选项D',
                            value: 'D',
                          },
                        ]}
                      />
                    </div>
                  </>
                )}
                {question.questionTypeId === 3 && (
                  <div className="judgment-answer">
                    <ProFormRadio.Group
                      name={question.questionId}
                      label=""
                      options={[
                        {
                          label: '正确',
                          value: 'true',
                        },
                        {
                          label: '错误',
                          value: 'false',
                        },
                      ]}
                    />
                  </div>
                )}
                {question.questionTypeId === 6 && (
                  <div className="short-answer">
                    <ProFormTextArea
                      name={question.questionId}
                      label=""
                    >
                    </ProFormTextArea>
                  </div>
                )}
              </div>
            ))}
          </div>
        </div>
      </ModalForm>
    </>

  );
};

export default HomePage;
